package com.example.webapp.controler;

import com.example.webapp.bean.Exam;
import com.example.webapp.bean.Registration;
import com.example.webapp.bean.User;
import com.example.webapp.service.ExamService;
import com.example.webapp.service.RegistrationService;
import com.example.webapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
public class SignupControler {
    @Autowired
    private UserService userService;

    @Autowired
    private ExamService examService;

    @Autowired
    private RegistrationService registrationService;

    @CrossOrigin
    @PostMapping("/signup")
    @ResponseBody
    public String update(@RequestBody Map map){
        Integer StudentId= Integer.parseInt(((String) map.get("id")));
        Optional<User> Res=userService.selectUserid(StudentId);
        User ExamUser;
        if (!Res.isPresent()) {
            return "cannot";
        } else {
            ExamUser=Res.get();
        }

        Exam TargetExam;
        String name=(String) map.get("location")+(String) map.get("exam_date");
        TargetExam= examService.getExamByName(name);
        if(TargetExam==null){
            TargetExam=new Exam();
            TargetExam.setName(name);
            TargetExam.setStartTime((String) map.get("exam_date"));
            TargetExam.setTotalScore(100);
            examService.createExam(TargetExam);
        }
        TargetExam= examService.getExamByName(name);
        if(TargetExam==null){
            return "error";
        }

        List<Registration> AlreadySignedUp=registrationService.findRegistrationsByStudent_Id(StudentId);
        for(int i=0;i<AlreadySignedUp.size();i++){
            if(AlreadySignedUp.get(i).getExam().getId()==TargetExam.getId()){
                return "already";
            }
        }

        Registration TargetRegistration=new Registration();
        TargetRegistration.setExam(TargetExam);
        TargetRegistration.setStudent(ExamUser);
        TargetRegistration.setFeeStatus("done");
        registrationService.createRegistration(TargetRegistration);
        return "success";
    }
}
